// pages/house/punchCard/punchCard.js
const app = getApp();
const chooseLocation = requirePlugin('chooseLocation');
import api from "../../../common/api"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isSelectPoint: false,
    recommendAddress: '',
    city: '',
    district: '',
    houseId: '',
    requestId: '',
    portUserId: '',
    currentPoint: {
      name: '',
      longitude: 0,
      latitude: 0,
      img: '',
    },

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中...',
    })
    app.globalData.loginPromise.then(() => {
      app.mobileLogin(false, '', false)
        .then(() => {
          this.getInitInfo(options.scene)
            .then(() => {
              wx.hideLoading()
            })
            .catch(() => {
              wx.hideLoading()
              wx.showToast({
                icon: 'none',
                title: '二维码已失效，请重新生成',
              })
            })
        })
        .catch(() => {
          app.globalData.afterMobileAuthorCallBack = () => {
            wx.redirectTo({
              url: `pages/house/punchCard/punchCard?scene=${options.scene}`
            });
          };
        })
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const location = chooseLocation.getLocation(); // 如果点击确认选点按钮，则返回选点结果对象，否则返回null
    if (location) {
      this.handlePointInfo(location)
      this.setData({
        isSelectPoint: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    chooseLocation.setLocation(null)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  getInitInfo(id) {
    return new Promise((resolve, reject) => {
      api.getRequestData({
        requestId: id
      }, (res) => {
        if (res && res.data && res.data.content) {
          let result = res.data.content
          let address = result.address ? result.address.split('-') : [];
          this.setData({
            recommendAddress: address[2] || '',
            district: address[1] || '',
            city: address[0] || '',
            houseId: result.houseId || '',
            requestId: id || '',
            portUserId: result.portUserId || '',
          })
          resolve()
        } else {
          reject()
        }
      })
    })
  },

  // 复制地址
  onCopy() {
    const {
      recommendAddress,
      district,
      city
    } = this.data
    wx.setClipboardData({
      data: `${city} ${district} ${recommendAddress}` || '',
      success: () => {},
      fail: () => {}
    })
  },

  // 跳转地图选择坐标
  onSelect() {
    const key = 'XNIBZ-G6JCJ-2MLFB-FZ4DL-XD27J-QTFGF'; //使用在腾讯位置服务申请的key
    const referer = '树懒经纪人'; //调用插件的app的名称
    const category = '小区';
    wx.navigateTo({
      url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&category=${category}`
    });
  },

  // 再次跳转地图选择坐标
  onSelectAgain() {
    const key = 'XNIBZ-G6JCJ-2MLFB-FZ4DL-XD27J-QTFGF'; //使用在腾讯位置服务申请的key
    const referer = '树懒经纪人'; //调用插件的app的名称
    const category = '小区';
    const {
      currentPoint
    } = this.data
    const location = JSON.stringify({
      latitude: currentPoint.latitude,
      longitude: currentPoint.longitude
    });
    wx.navigateTo({
      url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&category=${category}&location=${location}`
    });
  },

  // 处理选择点位信息
  handlePointInfo(location) {
    const {
      address,
      latitude,
      longitude
    } = location || {}
    this.setData({
      currentPoint: {
        name: address,
        longitude,
        latitude,
        img: `https://api-dev.shulanfd.com/shulan-jjr-gateway/api/v1/hou/port/getStaticPic?size=320*220&zoom=16&center=${latitude},${longitude}&markers=color:blue|${latitude},${longitude}`
      }
    })
  },

  // 提交打卡
  onSubmit() {
    wx.showLoading({
      title: '打卡中...',
    })
    const {
      houseId,
      requestId,
      currentPoint,
      portUserId
    } = this.data
    api.clockCheck({
      houseId,
      lat: currentPoint.latitude,
      lng: currentPoint.longitude,
      requestId,
      portUserId,
    }, (res) => {
      wx.hideLoading()
      if (res && res.data && res.data.isSuccess) {
        wx.showToast({
          title: '打卡成功',
        })
      } else {
        wx.showToast({
          icon: 'none',
          title: '打卡失败，打卡点距离小区超过1000米',
        })
      }
    })
  }

})